<%@ page contentType="text/html;charset=UTF-8" %>
<script type="text/javascript">
var initCost = false;
$(document).ready(function() {

	$('#table').bootstrapTable({
			  //请求方法
				method: 'post',
				//类型json
				dataType: "json",
				contentType: "application/x-www-form-urlencoded",
                 //是否显示行间隔色
                striped: true,
                //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
                cache: false,
				//显示检索按钮
		        showSearch: true,
				//显示刷新按钮
				showRefresh: true,
				//显示切换手机试图按钮
				showToggle: true,
				//显示 内容列下拉框
				showColumns: true,
				//显示切换分页按钮
                //是否显示分页（*）  
                pagination: true, 
                
                pageList: [10, 25, 50, 100,"All"],
                //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
                url: "${ctx}/sys/archCostItem/data",
                //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
                //queryParamsType:'',   
                ////查询参数,每次调用是会带上这个参数，可自定义                         
                queryParams : function(params) {
                	var searchParam = $("#searchForm").serializeJSON();
                	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
                	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
                	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                    return searchParam;
                },
				onShowSearch: function () {
					$("#search-collapse").slideToggle();
				},
                //分页方式：client客户端分页，server服务端分页（*）
                sidePagination: "server",
                contextMenuTrigger:"right",//pc端 按右键弹出菜单
                contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
                contextMenu: '#context-menu',
                onContextMenuItem: function(row, $el){
                    if($el.data("item") == "edit"){
                    	edit(row.id);
                    } else if($el.data("item") == "delete"){
                        del(row.id);
                       
                    } 
                },
                
                columns: [{
			        checkbox: true
			       
			    },{
			        field: 'label',
			        title: '档案类型',
			        sortable:true
			    }, {
                    field: 'operate',
                    title: '操作',
                    align: 'center',
                    events: {
        		        'click .setDictValue': function (e, value, row, index) {
                            initCost = true;
                            $("#left").attr("class", "col-sm-6");
                            setTimeout(function(){
                                $("#right").fadeIn(800);
                            },800)
                            $("#dictValueName").html(row.label);
                            $("#dictValueId").val(row.id);
                            $('#archCostItemTable').bootstrapTable("refresh",{query:{archCostItemId:row.id}})
        		        }
        		    },
                    formatter:  function operateFormatter(value, row, index) {
        		        return [
    						<shiro:hasPermission name="sys:dict:edit"> 
    							'<a href="#" class="setDictValue"  title="管理款项"><i class="fa fa-cog"></i> </a>'
    						</shiro:hasPermission>
        		        ].join('');
        		    }
                }]
			});

		  $('#table').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
	                'check-all.bs.table uncheck-all.bs.table', function () {
	            $('#remove').prop('disabled', ! $('#table').bootstrapTable('getSelections').length);
	            $('#edit').prop('disabled', $('#table').bootstrapTable('getSelections').length!=1);
	        });

		  $("#search").click("click", function() {// 绑定查询按扭
			  $('#table').bootstrapTable('refresh');
			});
		  $("#reset").click("click", function() {// 绑定查询按扭
			  $("#searchForm  input").val("");
			  $("#searchForm  select").val("");
			  $('#table').bootstrapTable('refresh');
			});
		  
	});

  function getIdSelections() {
        return $.map($("#table").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }

  function refresh(){
      $('#table').bootstrapTable('refresh');
  }
function refreshDictValue(){
    $('#archCostItemTable').bootstrapTable("refresh");
}



function initSwitch(){
    $('.project_status_switch').bootstrapSwitch({
        onText : "是",      // 设置ON文本
        offText : "否",    // 设置OFF文本
        onColor : "success",// 设置ON文本颜色(info/success/warning/danger/primary)
        offColor : "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
        size : "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        // 当开关状态改变时触发
        onSwitchChange : function(event, state) {
            var changeId = event.target.id
            var changevalue = this.value;
            var rowDate = $("#archCostItemTable").bootstrapTable('getRowByUniqueId',changeId);
            if (state == true) {
                rowDate[changevalue] = "1"
            } else {
                rowDate[changevalue] = "0"
            }
            changeStatus(rowDate);
        }
    })
}

function changeStatus(obj) {
    $.ajax({
        type : "post",
        dataType : "json",
        url: "${ctx}/sys/archCostItem/changeStatus",
        cache: false,
        data : {jsonStr: JSON.stringify(obj)},
        success : function(data) {
            if(data.success){
                jp.success(data.msg);
            }else{
                jp.error(data.msg);
            }
        }
    });
}
$(document).ready(function() {
	var $dictValueTable =	$('#archCostItemTable').bootstrapTable({
			  //请求方法
				method: 'post',
				//类型json
				dataType: "json",
				contentType: "application/x-www-form-urlencoded",
                 //是否显示行间隔色
                striped: true,
                //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
                cache: false,    
                //是否显示分页（*）  
                pagination: false,   
                //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
                url: "${ctx}/sys/archCostItem/getArchCostItem",
                //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
                //queryParamsType:'',   
                ////查询参数,每次调用是会带上这个参数，可自定义                         
                queryParams : function(params) {
                    return {dictValueId:$("#dictValueId").val()};
                },
                uniqueId : 'id',
                onLoadSuccess: function(){
                //初始化switch开关按钮
                    initSwitch();
                    $("#archCostItemTable").find('select').each(function(){
                        $(this).val($(this).attr("data-value"));
                    })
                    $('select').change(function (event) {
                        var changeId = event.target.id
                        var changevalue = this.value;
                        var rowDate = $("#archCostItemTable").bootstrapTable('getRowByUniqueId',changeId);
                        rowDate['salesid'] = changevalue
                        changeStatus(rowDate);
                    })
                },
                //分页方式：client客户端分页，server服务端分页（*）
                sidePagination: "server",
                columns: [{
			        field: 'costitemName',
			        title: '款项名称'
			    }, {
			        field: 'selected',
			        title: '选择',
                    formatter: function project_status(value, row, index) {//状态栏格式化
                        if(initCost){
                            if(value == 1){//如果值是1则显示“是”
                                return "<input type='checkbox' checked class='project_status_switch' id='" + row.id + "' name='change' value='selected'>";
                            }else{//如果值是0默认则显示“否”
                                return "<input type='checkbox' class='project_status_switch' id='" + row.id + "' name='change' value='selected'>";
                            }
                        }
                    },
                    align: 'center'
			    },{
			    	field: 'status',
			        title: '启用',
                    formatter: function project_status(value, row, index) {//状态栏格式化
                        if(initCost){
                            if(value == 1){//如果值是1则显示“是”
                                return "<input type='checkbox' checked class='project_status_switch' id='" + row.id + "' name='change' value='status'>";
                            }else{//如果值是0默认则显示“否”
                                return "<input type='checkbox' class='project_status_switch' id='" + row.id + "' name='change' value='status'>";
                            }
                        }
                    },
                    align: 'center'
			    },{
                    field: 'salesid',
                    title: '方式',
                    formatter:function(value, row , index){
                            return "<select id='"+row.id+"' class='form-control' data-value='"+value+"'>" +
                                "<option value=''></option>" +
                                "<c:forEach items='${fns:getDictList(\"Sys_SaleMode\")}' var='dict'>" +
                                "<option value=\"${dict.value}\">${dict.label}</option>" +
                                " </c:forEach>" +
                                "</select>"
                        },
                    align: 'center'
                },

                    {
			    	field: 'in',
			        title: '债权',
                    formatter: function project_status(value, row, index) {//状态栏格式化
                        if(initCost){
                            if(value == 1){//如果值是1则显示“是”
                                return "<input type='checkbox' checked class='project_status_switch' id='" + row.id + "' name='change' value='in'>";
                            }else{//如果值是0默认则显示“否”
                                return "<input type='checkbox' class='project_status_switch' id='" + row.id + "' name='change' value='in'>";
                            }
                        }
                    },
                    align: 'center'

			    },{
			    	field: 'out',
			        title: '债务',
                    formatter: function project_status(value, row, index) {//状态栏格式化
                        if(initCost){
                            if(value == 1){//如果值是1则显示“是”
                                return "<input type='checkbox' checked class='project_status_switch' id='" + row.id + "' name='change' value='out'>";
                            }else{//如果值是0默认则显示“否”
                                return "<input type='checkbox' class='project_status_switch' id='" + row.id + "' name='change' value='out'>";
                            }
                        }
                },
                    align: 'center'
			    }, {
                    field: 'operate',
                    title: '操作',
                    align: 'center',
                    events: {
        		        'click .del': function (e, value, row, index) {
        		        	jp.confirm('确认要删除键值吗？',function(){
        		        		jp.loading();
        		        		$.get('${ctx}/sys/archCostItem/deleteCost?id='+row.id, function(data){
  	                    	  		if(data.success){
  	                    	  			$('#archCostItemTable').bootstrapTable("refresh");
  	                    	  			jp.success(data.msg);
  	                    	  		}else{
  	                    	  			jp.error(data.msg);
  	                    	  		}
  	                    	  	})
        		        	});
        		        }
        		    },
                    formatter:  function operateFormatter(value, row, index) {
        		        return [
        		        	<shiro:hasPermission name="sys:btArchCostItem:edit">
    						'<a href="#" class="del" title="删除" >[删除] </a>'
    						</shiro:hasPermission>
        		        ].join('');
        		    }
                }]
			
			});

		  $("#archCostItemButton").click(function(){
                jp.openCostSelectDialog(true,function(ids){
                    jp.loading();
                    $.post("${ctx}/sys/archCostItem/assignCost",{dictValueId:$("#dictValueId").val(), ids:ids},function(data){
                        if(data.success){
                            $('#archCostItemTable').bootstrapTable("refresh",{query:{dictValueId:$("#dictValueId").val()}});
                            jp.success(data.msg);
                        }else{
                            jp.error(data.msg);
                        }
                    })
                })
			});
		  
		  });

		
	</script>